import React, { useState, useEffect } from 'react';
import { Routes, Route, Link, useLocation } from 'react-router-dom';
import Warehouse3D from './components/Warehouse3D';
import StatisticsPanel from './components/StatisticsPanel';
import InfoPanel from './components/InfoPanel';
import PLCPanel from './components/PLCPanel';
import PLCQueue from './components/PLCQueue';
import PLCPage from './pages/PLCPage';
import DatabaseDebugPage from './pages/DatabaseDebugPage';
import EmptySlotsPage from './pages/EmptySlotsPage';
import UnissuedTasksPage from './pages/UnissuedTasksPage';
import TaskAuditPage from './pages/TaskAuditPage';
import RuleEnginePage from './pages/RuleEnginePage';

import { getAllSlots, initializeSlots, updateSlot as updateSlotAPI, getStatistics, getConfig, reinitializeData } from './services/api';
import { generateWarehouseData } from './utils/warehouseData';
import { formatToBeijingTime } from './utils/timeUtils';
import './App.css';

// 添加导入配置文件的函数
const loadConfigFromFile = async () => {
  try {
    // 使用API函数获取配置文件，避免缓存问题
    const config = await getConfig();
    return config;
  } catch (err) {
    console.warn('无法加载配置文件，使用默认配置:', err);
  }
  // 默认配置
  return { rows: 4, columns: 8, layers: 4, goodsRate: 70 };
};

// 导航组件
function Navigation() {
  const location = useLocation();
  
  return (
    <nav style={{
      position: 'fixed',
      top: '20px',
      left: '20px',
      zIndex: 1000,
      background: 'rgba(30, 30, 30, 0.9)',
      padding: '10px 15px',
      borderRadius: '10px',
      border: '2px solid #2196F3',
      backdropFilter: 'blur(10px)'
    }}>
      <ul style={{
        listStyle: 'none',
        margin: 0,
        padding: 0,
        display: 'flex',
        flexDirection: 'column',
        gap: '10px'
      }}>
        <li>
          <Link to="/" style={{
            color: location.pathname === '/' ? '#2196F3' : '#aaa',
            textDecoration: 'none',
            fontWeight: location.pathname === '/' ? 'bold' : 'normal',
            fontSize: '14px'
          }}>
            🏠 主页
          </Link>
        </li>
        <li>
          <Link to="/plc" style={{
            color: location.pathname === '/plc' ? '#2196F3' : '#aaa',
            textDecoration: 'none',
            fontWeight: location.pathname === '/plc' ? 'bold' : 'normal',
            fontSize: '14px'
          }}>
            🔄 PLC控制
          </Link>
        </li>
        <li>
          <Link to="/node-red" style={{
            color: location.pathname === '/node-red' ? '#2196F3' : '#aaa',
            textDecoration: 'none',
            fontWeight: location.pathname === '/node-red' ? 'bold' : 'normal',
            fontSize: '14px'
          }}>
            🔧 Node-RED
          </Link>
        </li>
        <li>
          <a href="http://localhost:1880/api/ui" target="_blank" rel="noopener noreferrer" style={{
            color: '#aaa',
            textDecoration: 'none',
            fontWeight: 'normal',
            fontSize: '14px'
          }}>
            🎛️ Node-UI
          </a>
        </li>
        <li>
          <Link to="/queue-status" style={{
            color: location.pathname === '/queue-status' ? '#2196F3' : '#aaa',
            textDecoration: 'none',
            fontWeight: location.pathname === '/queue-status' ? 'bold' : 'normal',
            fontSize: '14px'
          }}>
            📋 队列状态
          </Link>
        </li>
        <li>
          <Link to="/db-debug" style={{
            color: location.pathname === '/db-debug' ? '#2196F3' : '#aaa',
            textDecoration: 'none',
            fontWeight: location.pathname === '/db-debug' ? 'bold' : 'normal',
            fontSize: '14px'
          }}>
            🗄️ 数据库调试
          </Link>
        </li>
        <li>
          <Link to="/empty-slots" style={{
            color: location.pathname === '/empty-slots' ? '#2196F3' : '#aaa',
            textDecoration: 'none',
            fontWeight: location.pathname === '/empty-slots' ? 'bold' : 'normal',
            fontSize: '14px'
          }}>
            📦 无货货位
          </Link>
        </li>
        <li>
          <Link to="/unissued-tasks" style={{
            color: location.pathname === '/unissued-tasks' ? '#2196F3' : '#aaa',
            textDecoration: 'none',
            fontWeight: location.pathname === '/unissued-tasks' ? 'bold' : 'normal',
            fontSize: '14px'
          }}>
            📋 未下发任务
          </Link>
        </li>
        <li>
          <Link to="/task-audit" style={{
            color: location.pathname === '/task-audit' ? '#2196F3' : '#aaa',
            textDecoration: 'none',
            fontWeight: location.pathname === '/task-audit' ? 'bold' : 'normal',
            fontSize: '14px'
          }}>
            📊 任务审计
          </Link>
        </li>
        <li>
          <Link to="/rule-engine" style={{
            color: location.pathname === '/rule-engine' ? '#2196F3' : '#aaa',
            textDecoration: 'none',
            fontWeight: location.pathname === '/rule-engine' ? 'bold' : 'normal',
            fontSize: '14px'
          }}>
            🤖 规则引擎
          </Link>
        </li>
      </ul>
    </nav>
  );
}

function HomePage() {
  const [warehouseData, setWarehouseData] = useState(null);
  const [selectedSlot, setSelectedSlot] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isInitialized, setIsInitialized] = useState(false);
  const [mousePosition, setMousePosition] = useState({ x: 200, y: 200 }); // 默认位置
  
  // 更新鼠标位置
  useEffect(() => {
    const handleMouseMove = (event) => {
      setMousePosition({ x: event.clientX, y: event.clientY });
    };
    
    window.addEventListener('mousemove', handleMouseMove);
    
    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
    };
  }, []);

  // 组件加载时从数据库读取数据
  useEffect(() => {
    const initApp = async () => {
      // 首先尝试从配置文件加载默认配置
      const loadedFileConfig = await loadConfigFromFile();
      
      // 如果数据库为空，使用配置文件中的配置初始化数据
      const data = await getAllSlots();
      if (!data.slotsArray || data.slotsArray.length === 0) {
        await initializeData(loadedFileConfig);
      } else {
        loadDataFromDB();
      }
    };
    
    initApp();
  }, []);

  // 从数据库加载数据
  const loadDataFromDB = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const data = await getAllSlots();
      // 获取统计信息
      const stats = await getStatistics();
      
      // 修复：正确处理数据结构
      if (data && data.slotsArray && data.slotsArray.length > 0) {
        // 计算仓库配置 (使用1基索引)
        const maxLayer = Math.max(...data.slotsArray.map(s => s.layer));
        const maxRow = Math.max(...data.slotsArray.map(s => s.row));
        const maxCol = Math.max(...data.slotsArray.map(s => s.column));
        
        const warehouseConfig = {
          rows: maxRow,
          columns: maxCol,
          layers: maxLayer,
          slots: data.slots || {},
          totalSlots: stats.totalSlots || 0,
          occupiedSlots: stats.occupiedSlots || 0,
          emptySlots: stats.emptySlots || 0,
          occupancyRate: stats.occupancyRate || '0.00',
          layerStatistics: stats.layerStatistics || []
        };
        
        setWarehouseData(warehouseConfig);
        setIsInitialized(true);
        console.log('✅ 从数据库加载数据成功');
      } else {
        // 数据库为空，使用配置文件中的配置初始化数据
        const config = await loadConfigFromFile();
        await initializeData(config);
      }
    } catch (err) {
      console.error('从数据库加载失败,使用本地数据:', err);
      setError('无法连接到数据库,使用本地模式');
      // 使用本地数据: 4排货架
      const data = generateWarehouseData(4, 8, 4);
      setWarehouseData(data);
    } finally {
      setLoading(false);
    }
  };

  // 初始化数据到数据库
  const initializeData = async (config) => {
    try {
      console.log('🔄 初始化数据库...');
      
      console.log('使用配置:', config);
      console.log(`配置详情 - 排数: ${config.rows}, 列数: ${config.columns}, 层数: ${config.layers}`);
      
      // 使用配置生成数据，包括货物比例
      const goodsRate = config.goodsRate !== undefined ? config.goodsRate : 70;
      const generatedData = generateWarehouseData(
        config.rows, 
        config.columns, 
        config.layers,
        goodsRate
      );
      
      console.log('生成的数据详情:', {
        rows: generatedData.rows,
        columns: generatedData.columns,
        layers: generatedData.layers,
        totalSlots: generatedData.totalSlots
      });
      
      // 传递正确的数据格式给API
      const apiData = {
        rows: config.rows,
        columns: config.columns,
        layers: config.layers,
        slots: generatedData.slots
      };
      
      await initializeSlots(apiData);
      
      setWarehouseData(generatedData);
      setIsInitialized(true);
      console.log('✅ 数据库初始化成功');
    } catch (err) {
      console.error('数据库初始化失败:', err);
      setError('数据库初始化失败');
      throw err;
    }
  };

  const handleSlotClick = (slotId, slotInfo) => {
    // 如果点击的是空区域，取消选中
    if (slotId === null) {
      setSelectedSlot(null);
      return;
    }
    
    // 修复：确保slotId是字符串类型并设置选中状态
    console.log(`选中货位: ${slotId}`);
    setSelectedSlot(String(slotId));
  };

  const handleCloseInfo = () => {
    setSelectedSlot(null);
  };

  // 更新货位状态（同时更新数据库）
  const handleUpdateSlot = async (slotId, hasGoods, goodsInfo) => {
    try {
      // 更新数据库
      await updateSlotAPI(slotId, hasGoods, goodsInfo);
      
      // 重新加载数据
      await loadDataFromDB();
      
      console.log('✅ 货位更新成功');
    } catch (err) {
      console.error('更新货位失败:', err);
      alert('更新货位失败: ' + err.message);
    }
  };

  // 重新加载数据的函数
  const handleRefresh = async () => {
    await loadDataFromDB();
  };

  // 重新初始化数据的函数
  const handleReinitialize = async () => {
    if (window.confirm('确定要重新初始化数据吗？这将清空现有数据并根据配置文件重新生成！')) {
      try {
        setLoading(true);
        // 调用服务器端的重新初始化API
        await reinitializeData();
        // 重新加载数据
        await loadDataFromDB();
        alert('数据重新初始化成功！');
      } catch (err) {
        console.error('重新初始化失败:', err);
        alert('重新初始化失败: ' + err.message);
      } finally {
        setLoading(false);
      }
    }
  };

  if (loading) {
    return (
      <div style={{
        width: '100vw',
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#1a1a1a',
        color: '#fff',
        fontSize: '24px',
        gap: '20px'
      }}>
        <div>🔄 加载中...</div>
        {error && (
          <div style={{ fontSize: '14px', color: '#ff9800' }}>
            {error}
          </div>
        )}
      </div>
    );
  }

  if (!warehouseData) {
    return (
      <div style={{
        width: '100vw',
        height: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#1a1a1a',
        color: '#fff',
        fontSize: '18px'
      }}>
        ❌ 加载数据失败
      </div>
    );
  }

  return (
    <div style={{ width: '100vw', height: '100vh', position: 'relative', background: '#1a1a1a' }}>
      {/* 页面标题和状态 */}
      <div style={{
        position: 'fixed',
        top: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 1000,
        background: 'rgba(30, 30, 30, 0.9)',
        padding: '15px 30px',
        borderRadius: '10px',
        border: '2px solid #2196F3',
        backdropFilter: 'blur(10px)',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: '5px'
      }}>
        <h1 style={{
          margin: 0,
          color: '#2196F3',
          fontSize: '28px',
          textAlign: 'center'
        }}>
          3D立体库货位管理系统
        </h1>
        <div style={{
          fontSize: '12px',
          color: isInitialized ? '#4CAF50' : '#ff9800',
          display: 'flex',
          alignItems: 'center',
          gap: '5px'
        }}>
          {isInitialized ? '🗄️ 数据库已连接' : '⚠️ 本地模式'}
          {error && ` - ${error}`}
        </div>
      </div>

      {/* 控制按钮 - 右上方 */}
      <div style={{
        position: 'fixed',
        top: '100px',
        right: '20px',
        zIndex: 900,
        display: 'flex',
        flexDirection: 'column',
        gap: '10px'
      }}>
        <button 
          onClick={handleRefresh}
          style={{
            padding: '10px 15px',
            backgroundColor: '#2196F3',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer',
            fontWeight: 'bold'
          }}
        >
          🔄 刷新数据
        </button>
        <button 
          onClick={handleReinitialize}
          style={{
            padding: '10px 15px',
            backgroundColor: '#FF9800',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer',
            fontWeight: 'bold'
          }}
        >
          🔄 重新初始化
        </button>
      </div>

      {/* 3D场景 */}
      <Warehouse3D
        warehouseData={warehouseData}
        onSlotClick={handleSlotClick}
        selectedSlot={selectedSlot}
      />

      {/* 统计面板 - 底部 */}
      <div style={{
        position: 'fixed',
        bottom: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 900,
        minWidth: '800px'
      }}>
        <StatisticsPanel warehouseData={warehouseData} />
      </div>

      {/* 货位信息面板 - 右侧 */}
      {selectedSlot && warehouseData && warehouseData.slots && warehouseData.slots[selectedSlot] && (
        <InfoPanel
          selectedSlot={selectedSlot}
          warehouseData={warehouseData}
          onClose={handleCloseInfo}
          onUpdateSlot={handleUpdateSlot}
          mousePosition={mousePosition}
        />
      )}
    </div>
  );
}

// Node-RED集成页面组件
function NodeRedPage() {
  return (
    <div style={{ width: '100vw', height: '100vh', position: 'relative' }}>
      {/* 页面标题和返回按钮 */}
      <div style={{
        position: 'fixed',
        top: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 1000,
        background: 'rgba(30, 30, 30, 0.9)',
        padding: '15px 30px',
        borderRadius: '10px',
        border: '2px solid #2196F3',
        backdropFilter: 'blur(10px)',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: '10px'
      }}>
        <h1 style={{
          margin: 0,
          color: '#2196F3',
          fontSize: '24px',
          textAlign: 'center'
        }}>
          Node-RED 低代码开发平台
        </h1>
        <div style={{ display: 'flex', gap: '10px' }}>
          <Link to="/" style={{
            padding: '8px 16px',
            background: '#4CAF50',
            color: 'white',
            textDecoration: 'none',
            borderRadius: '4px',
            fontWeight: 'bold'
          }}>
            🏠 返回主页
          </Link>
          <a href="http://localhost:1880/red" target="_blank" rel="noopener noreferrer" style={{
            padding: '8px 16px',
            background: '#FF9800',
            color: 'white',
            textDecoration: 'none',
            borderRadius: '4px',
            fontWeight: 'bold'
          }}>
            🌐 在新窗口打开
          </a>
        </div>
      </div>

      {/* Node-RED iframe */}
      <iframe 
        src="http://localhost:1880/red" 
        title="Node-RED"
        style={{
          width: '100%',
          height: '100%',
          border: 'none',
          marginTop: '100px'
        }}
      />
    </div>
  );
}

// 队列状态页面组件
function QueueStatusPage() {
  const [queueStatus, setQueueStatus] = useState(null);
  const [queueHistory, setQueueHistory] = useState([]);
  const [activeTab, setActiveTab] = useState('status'); // 'status' or 'history'
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 格式化耗时显示
  const formatDuration = (duration) => {
    if (duration === undefined) return 'N/A';
    if (duration < 1000) {
      return `${duration}ms`;
    } else {
      return `${(duration / 1000).toFixed(2)}s`;
    }
  };

  useEffect(() => {
    const fetchQueueStatus = async () => {
      try {
        setLoading(true);
        // 修复：使用绝对URL而不是相对路径
        const response = await fetch('http://localhost:3003/api/queue/status');
        if (response.ok) {
          const data = await response.json();
          setQueueStatus(data);
        } else {
          throw new Error('获取队列状态失败');
        }
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    const fetchQueueHistory = async () => {
      try {
        const response = await fetch('http://localhost:3003/api/queue/history');
        if (response.ok) {
          const data = await response.json();
          // 修复：正确设置历史记录数据
          setQueueHistory(data.data || []);
        }
      } catch (err) {
        console.error('获取队列历史记录失败:', err);
      }
    };

    // 初次加载
    fetchQueueStatus();
    fetchQueueHistory();
    
    // 每5秒刷新一次
    const interval = setInterval(() => {
      fetchQueueStatus();
      fetchQueueHistory();
    }, 5000);
    
    return () => clearInterval(interval);
  }, []);

  return (
    <div style={{ width: '100vw', height: '100vh', position: 'relative' }}>
      {/* 页面标题和返回按钮 */}
      <div style={{
        position: 'fixed',
        top: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 1000,
        background: 'rgba(30, 30, 30, 0.9)',
        padding: '15px 30px',
        borderRadius: '10px',
        border: '2px solid #2196F3',
        backdropFilter: 'blur(10px)',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: '10px'
      }}>
        <h1 style={{
          margin: 0,
          color: '#2196F3',
          fontSize: '24px',
          textAlign: 'center'
        }}>
          队列服务状态监控
        </h1>
        <div style={{ display: 'flex', gap: '10px' }}>
          <Link to="/" style={{
            padding: '8px 16px',
            background: '#4CAF50',
            color: 'white',
            textDecoration: 'none',
            borderRadius: '4px',
            fontWeight: 'bold'
          }}>
            🏠 返回主页
          </Link>
          <button 
            onClick={() => window.location.reload()}
            style={{
              padding: '8px 16px',
              background: '#2196F3',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              fontWeight: 'bold',
              cursor: 'pointer'
            }}
          >
            🔄 刷新
          </button>
        </div>
      </div>

      

      {/* 标签页切换 */}
      <div style={{
        position: 'fixed',
        top: '140px',
        left: '50%',
        transform: 'translateX(-50%)',
        width: '80%',
        maxWidth: '1000px',
        display: 'flex',
        gap: '2px',
        zIndex: 900
      }}>
        <button
          onClick={() => setActiveTab('status')}
          style={{
            flex: 1,
            padding: '12px',
            background: activeTab === 'status' ? '#2196F3' : '#555',
            color: 'white',
            border: 'none',
            cursor: 'pointer',
            fontWeight: 'bold',
            borderTopLeftRadius: '5px',
            borderTopRightRadius: activeTab === 'status' ? '0' : '5px'
          }}
        >
          当前状态
        </button>
        <button
          onClick={() => setActiveTab('history')}
          style={{
            flex: 1,
            padding: '12px',
            background: activeTab === 'history' ? '#2196F3' : '#555',
            color: 'white',
            border: 'none',
            cursor: 'pointer',
            fontWeight: 'bold',
            borderTopLeftRadius: activeTab === 'history' ? '0' : '5px',
            borderTopRightRadius: '5px'
          }}
        >
          历史记录
        </button>
      </div>

      {/* 状态显示区域 */}
      <div style={{
        position: 'fixed',
        top: '160px',
        left: '50%',
        transform: 'translateX(-50%)',
        width: '80%',
        maxWidth: '1000px',
        background: 'rgba(30, 30, 30, 0.9)',
        padding: '20px',
        borderRadius: '10px',
        border: '2px solid #2196F3',
        backdropFilter: 'blur(10px)',
        maxHeight: 'calc(100vh - 320px)',
        overflowY: 'auto'
      }}>
        {activeTab === 'status' ? (
          <>
            {loading ? (
              <div style={{ textAlign: 'center', color: '#fff', fontSize: '18px' }}>
                🔄 正在加载队列状态...
              </div>
            ) : error ? (
              <div style={{ textAlign: 'center', color: '#f44336', fontSize: '18px' }}>
                ❌ {error}
              </div>
            ) : queueStatus ? (
              <div>
                <h2 style={{ color: '#fff', textAlign: 'center' }}>队列状态信息</h2>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '20px', marginTop: '20px' }}>
                  <div style={{ background: '#4CAF50', padding: '15px', borderRadius: '5px', textAlign: 'center' }}>
                    <div style={{ fontSize: '24px', fontWeight: 'bold' }}>{queueStatus.queueLength}</div>
                    <div>待处理任务数</div>
                  </div>
                  <div style={{ background: queueStatus.processing ? '#FF9800' : '#4CAF50', padding: '15px', borderRadius: '5px', textAlign: 'center' }}>
                    <div style={{ fontSize: '24px', fontWeight: 'bold' }}>
                      {queueStatus.processing ? '处理中' : '空闲'}
                    </div>
                    <div>处理状态</div>
                  </div>
                </div>
                
                <h3 style={{ color: '#fff', marginTop: '30px' }}>待处理任务列表</h3>
                {queueStatus.pendingTasks && queueStatus.pendingTasks.length > 0 ? (
                  <div style={{ marginTop: '15px' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse', color: '#fff' }}>
                      <thead>
                        <tr style={{ background: '#2196F3' }}>
                          <th style={{ padding: '10px', textAlign: 'left' }}>任务ID</th>
                          <th style={{ padding: '10px', textAlign: 'left' }}>任务类型</th>
                          <th style={{ padding: '10px', textAlign: 'left' }}>添加时间</th>
                        </tr>
                      </thead>
                      <tbody>
                        {queueStatus.pendingTasks.map((task, index) => (
                          <tr key={task.id} style={{ background: index % 2 === 0 ? '#444' : '#333' }}>
                            <td style={{ padding: '10px' }}>{task.id}</td>
                            <td style={{ padding: '10px' }}>{task.type}</td>
                            <td style={{ padding: '10px' }}>{formatToBeijingTime(task.timestamp)}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <div style={{ textAlign: 'center', color: '#aaa', marginTop: '15px' }}>
                    当前没有待处理的任务
                  </div>
                )}
              </div>
            ) : (
              <div style={{ textAlign: 'center', color: '#fff', fontSize: '18px' }}>
                无法获取队列状态信息
              </div>
            )}
          </>
        ) : (
          // 历史记录标签页内容
          <div>
            <h2 style={{ color: '#fff', textAlign: 'center' }}>历史任务记录</h2>
            {queueHistory && queueHistory.length > 0 ? (
              <div style={{ marginTop: '15px' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', color: '#fff' }}>
                  <thead>
                    <tr style={{ background: '#2196F3' }}>
                      <th style={{ padding: '10px', textAlign: 'left' }}>任务ID</th>
                      <th style={{ padding: '10px', textAlign: 'left' }}>任务类型</th>
                      <th style={{ padding: '10px', textAlign: 'left' }}>状态</th>
                      <th style={{ padding: '10px', textAlign: 'left' }}>耗时</th>
                      <th style={{ padding: '10px', textAlign: 'left' }}>时间</th>
                    </tr>
                  </thead>
                  <tbody>
                    {queueHistory.map((task, index) => (
                      <tr key={task.id} style={{ background: index % 2 === 0 ? '#444' : '#333' }}>
                        <td style={{ padding: '10px' }}>{task.id}</td>
                        <td style={{ padding: '10px' }}>{task.task?.type || '未知'}</td>
                        <td style={{ padding: '10px' }}>
                          <span style={{
                            padding: '3px 8px',
                            borderRadius: '3px',
                            backgroundColor: task.status === 'completed' ? '#4CAF50' : '#f44336'
                          }}>
                            {task.status === 'completed' ? '完成' : '失败'}
                          </span>
                        </td>
                        <td style={{ padding: '10px' }}>{formatDuration(task.duration)}</td>
                        <td style={{ padding: '10px' }}>{formatToBeijingTime(task.timestamp)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <div style={{ textAlign: 'center', color: '#aaa', marginTop: '15px' }}>
                暂无历史任务记录
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function App() {
  return (
    <div>
      <Navigation />
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/plc" element={<PLCPage />} />
        <Route path="/plc-test" element={<PLCQueue />} />
        <Route path="/node-red" element={<NodeRedPage />} />
        <Route path="/queue-status" element={<QueueStatusPage />} />
        <Route path="/db-debug" element={<DatabaseDebugPage />} />
        <Route path="/empty-slots" element={<EmptySlotsPage />} />
        <Route path="/unissued-tasks" element={<UnissuedTasksPage />} />
        <Route path="/task-audit" element={<TaskAuditPage />} />
        <Route path="/rule-engine" element={<RuleEnginePage />} />
      </Routes>
    </div>
  );
}

export default App;